#include "BlockQueue.hpp"
#include <pthread.h>
#include <unistd.h>
#include "Task.hpp"

int myAdd(int x, int y)
{
    return x + y;
}
void *consumer(void *args)
{
    sleep(3);
    BlockQueue<Task> *pbqueue = (BlockQueue<Task> *)args;
    while (true)
    {
        Task t;
        pbqueue->pop(&t);
        // std::cout << "消费一个数据：" << a << std::endl;
        // printf("消费一个数据：%d\n", a);

        std::cout << pthread_self() << " consumer: " << t._x << "+" << t._y << "=" << t() << std::endl;
        sleep(1);
    }
    return nullptr;
}

void *productor(void *args)
{
    //sleep(5);
    BlockQueue<Task> *pbqueue = (BlockQueue<Task> *)args;
    // int a = 1;
    while (true)
    {
        // std::cout << "生产一个数据：" << a << std::endl;
        int x = rand() % 10 + 1;
        usleep(rand() % 1000);
        int y = rand() % 10 + 1;
        Task t(x, y, myAdd);

        std::cout << pthread_self() << " productor: " << t._x << "+" << t._y << "=?" << std::endl;
        pbqueue->push(t);
        //sleep(1);

        // printf("生产一个数据：%d\n", a);
        // a++;
    }
    return nullptr;
}

int main()
{
    srand((uint64_t)time(nullptr) ^ getpid() ^ 0x125542);
    BlockQueue<Task> bqueue;

    pthread_t c, p;
    pthread_create(&c, nullptr, consumer, &bqueue);
    pthread_create(&p, nullptr, productor, &bqueue);

    pthread_join(c, nullptr);
    pthread_join(p, nullptr);

    // pthread_t c[2], p[2];
    // pthread_create(c, nullptr, consumer, &bqueue);
    // pthread_create(c + 1, nullptr, consumer, &bqueue);
    // pthread_create(p, nullptr, productor, &bqueue);
    // pthread_create(p + 1, nullptr, productor, &bqueue);

    // pthread_join(c[0], nullptr);
    // pthread_join(c[1], nullptr);
    // pthread_join(p[0], nullptr);
    // pthread_join(p[1], nullptr);

    return 0;
}